<?php
include "../includes/common.php";
if ($islogin2 == 1) {} else {
    exit('{"code":-3,"msg":"No Login"}');
}
$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;
@header('Content-Type: application/json; charset=UTF-8');
switch ($act) {
    case 'sendcode':
        $sendemail= function ($arr){
            require_once("../vendor/PHPMailer/src/PHPMailer.php");
            require_once("../vendor/PHPMailer/src/SMTP.php");

            $mail = new  PHPMailer();
            $mail->isSMTP();
            $mail->Username = $arr['formqq'];
            $mail->Password = $arr['formpwd'];
            $mail->From = $mail->Username;
            $mail->FromName = '';
            $mail->SMTPAuth = true;
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = $arr['form'];
            $mail->CharSet = 'UTF-8';
            $mail->isHTML(true);
            $mail->addAddress("{$arr['address']}");
            $mail->Subject =$arr['fromname'];
            $mail->Body = "<h1>{$arr['content']}</h1>";
            return $mail->send();

        };


        $situation = trim($_POST['situation']);
        $email=trim($_POST['email']);
        $code = mt_rand(1111111, 9999999);
        $sub  = $conf['web_name'] . ' - 验证码获取';
       if ($situation == 'settle') {
            $msg = '您正在修改结算账号信息，验证码是：' . $code;
        } elseif ($situation == 'mibao') {
            $msg = '您正在修改邮箱，验证码是：' . $code;
        } elseif ($situation == 'bind') {
            $msg = '您正在绑定新邮箱，验证码是：' . $code;
        } else {
            $msg = '您的验证码是：' . $code;
        }
        if(isset($_SESSION['send_mail'])){
            if($_SESSION['send_mail']+60>time() ){
                exit('{"code":-1,"msg":"发送过于频繁"}');
            }
        }
    
        $webconf=$conf;
        try{
            $sendemail(array( 'address'=>$email,'content'=>$msg,'formqq'=>$webconf['mail_name'],'formpwd'=>$webconf['mail_pwd'],'form'=>$webconf['mail_port'],'fromname'=>$webconf['web_name']));
        }catch(\Exception $e){
            exit('{"code":-1,"msg":"发送失败"}');
        }

        $getip=function() {
            if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
                $ip = getenv('HTTP_CLIENT_IP');
            } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
                $ip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
                $ip = getenv('REMOTE_ADDR');
            } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
            $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
            return $res;
        };

 
        $sendip=$getip();
        $time=time();
        $sql="insert into `pay_regcode` (`type`,`code`,`email`,`time`,`ip`,`status`) values ('2','{$code}','{$email}','{$time}','{$sendip}','0') ";
        if ($DB->exec($sql)) {
            $_SESSION['send_mail'] = time();
            exit('{"code":0,"msg":"succ"}');
        } else {

            exit('{"code":-1,"msg":"写入数据库失败。' . $DB->errorCode() . '"}');
        }
        exit('{"code":0,"msg":"succ"}');

        break;
    case 'verifycode':
        $code = trim($_POST['code']);
        if ($conf['verifytype'] == 1) {
            $row = $DB->query("select * from pay_regcode where type=2 and code='$code'  order by id desc limit 1")->fetch();
        } else {
            $row = $DB->query("select * from pay_regcode where type=2 and code='$code'  order by id desc limit 1")->fetch();
        }

        if (!$row) {
            exit('{"code":-1,"msg":"验证码不正确！"}');
        }
        if ($row['time'] < time() - 3600 || $row['status'] > 0) {
            exit('{"code":-1,"msg":"验证码已失效，请重新获取"}');
        }
        $_SESSION['verify_ok'] = $pid;
        $DB->exec("update `pay_regcode` set `status` ='1' where `id`='{$row['id']}'");
        exit('{"code":1,"msg":"succ"}');
        break;
    case 'setemail':
        $email=trim($_POST['email']);
        $userid=$pid;

        if(!$email || !$userid){
            exit('{"code":0,"msg":"参数不足"}');
        }

        $row = $DB->query("select * from pay_user where name='{$userid}'  limit 1")->fetch();

        if($row['email']){
            $res=$DB->exec("update `pay_user` set `email` ='' where `id`='{$row['id']}'");
        }else{
            $roe = $DB->query("select * from pay_user where email='$email' limit 1")->fetch();
            if ($roe['email']) {
                exit('{"code":-1,"msg":"该邮箱已经绑定过其它商户"}');
            }

            $res=$DB->exec("update `pay_user` set `email` ='{$email}' where `id`='{$row['id']}'");
        }
        if($res){
            exit('{"code":1,"msg":"succ"}');
        }
        exit('{"code":-1,"msg":"操作失败"}');
        break;

    case 'edit_settle':
        $type     = intval($_POST['stype']);
        $account  = trim(strip_tags(daddslashes($_POST['account'])));
        $username = trim(strip_tags(daddslashes($_POST['username'])));

        if ($account == null || $username == null) {
            exit('{"code":-1,"msg":"请确保每项都不为空"}');
        }
        if ($type == 1 && strlen($account) != 11 && strpos($account, '@') == false) {
            exit('{"code":-1,"msg":"请填写正确的支付宝账号！"}');
        }
        if ($type == 2 && strlen($account) < 3) {
            exit('{"code":-1,"msg":"请填写正确的微信"}');
        }

        if (empty($userrow['email'])) {
            exit('{"code":-1,"msg":"请先绑定邮箱！"}');
        }

        $sqs = $DB->exec("update `pay_user` set `settle_id` ='{$type}',`account` ='{$account}',`username` ='{$username}' where `name`='$pid'");
        if ($sqs || $DB->errorCode() == '0000') {
            exit('{"code":1,"msg":"succ"}');
        } else {
            exit('{"code":-1,"msg":"保存失败！' . $DB->errorCode() . '"}');
        }

        break;

      case 'edit_pass':
        $pass  = md5(trim(strip_tags(daddslashes($_POST['pass']))));
      

        if ($pass == null) {
            exit('{"code":-1,"msg":"请确保每项都不为空"}');
        }

        if (empty($userrow['email'])) {
            exit('{"code":-1,"msg":"请先绑定邮箱！"}');
        }

        $sqs = $DB->exec("update `pay_user` set `pass` ='{$pass}' where `name`='$pid'");
        if ($sqs || $DB->errorCode() == '0000') {
            exit('{"code":1,"msg":"succ"}');
        } else {
            exit('{"code":-1,"msg":"保存失败！' . $DB->errorCode() . '"}');
        }
        break;


    // case 'edit_safecode':
    //     $safecode = trim(strip_tags(daddslashes($_POST['safecode'])));

    //     if($safecode == null){
    //         exit('{"code":-1,"msg":"请确保每项都不为空"}');
    //     }elseif(empty($userrow['email']) || strpos($userrow['email'],'@')===false){
    //         exit('{"code":-1,"msg":"请先绑定邮箱！"}');
    //     }

    //     $sqs=$DB->exec("update `pay_user` set `safecode` ='{$safecode}' where `name`='$pid'");
    //     if($sqs || $DB->errorCode()=='0000'){
    //         exit('{"code":1,"msg":"succ"}');
    //     }else{
    //         exit('{"code":-1,"msg":"保存失败！'.$DB->errorCode().'"}');
    //     }
    //     break;
    case 'tosafecode':
        $safecode = trim(strip_tags(daddslashes($_POST['safecode'])));
        if ($safecode == null){
            exit('{"code":-1,"msg":"请确保每项都不为空"}');
        }
        $token = md5($safecode.$password_hash);
        if ($safecode == $userrow['safecode']){
            setcookie("safecode", $token, time() + 604800);
            exit('{"code":1,"msg":"验证成功！"}');
        }else{
            exit('{"code":0,"msg":"验证失败，安全码错误！"}');
        }
        break;
    case 'edit_info':
        $email = daddslashes(strip_tags($_POST['email']));
        $qq    = daddslashes(strip_tags($_POST['qq']));
        $url   = daddslashes(strip_tags($_POST['url']));
        $safecode = trim(strip_tags(daddslashes($_POST['safecode'])));
		$pwd  = daddslashes($_POST['pwd']);
        $pwdw =md5($pwd);
   
        if ($qq == null || $url == null) {
            exit('{"code":-1,"msg":"请确保每项都不为空"}');
        }
		
		if(empty($pwd)){
        if ($conf['verifytype'] == 1) {
       $sqs = $DB->exec("update `pay_user` set `email` ='{$email}',`qq` ='{$qq}',`url` ='{$url}',`safecode` ='{$safecode}' where `name`='$pid'");
        } else {
            $sqs = $DB->exec("update `pay_user` set `qq` ='{$qq}',`url` ='{$url}',`safecode` ='{$safecode}' where `name`='$pid'");
        }
        if ($sqs || $DB->errorCode()=='0000') {
            exit('{"code":1,"msg":"商户信息设置成功!"}');

        } else {
            exit('{"code":-1,"msg":"保存失败！' . $DB->errorCode() . '"}');
        }
		}else{
       $sqs = $DB->exec("update `pay_user` set `email` ='{$email}',`qq` ='{$qq}',`url` ='{$url}',`safecode` ='{$safecode}',`pwd` ='{$pwdw}'  where `name`='$pid'");
        if ($sqs || $DB->errorCode()=='0000') {
            exit('{"code":1,"msg":"商户信息设置成功!"}');

        } else {
            exit('{"code":-1,"msg":"保存失败！' . $DB->errorCode() . '"}');
        }		
			
		}
        break;
    case 'edit_bind':
        $email = daddslashes(strip_tags($_POST['email']));
        $phone = daddslashes(strip_tags($_POST['phone']));
        $code  = daddslashes(strip_tags($_POST['code']));

        if ($code == null || $email == null && $phone == null) {
            exit('{"code":-1,"msg":"请确保每项都不为空"}');
        }
        if ($conf['verifytype'] == 1) {
            $row = $DB->query("select * from pay_regcode where type=3 and code='$code' and email='$phone' order by id desc limit 1")->fetch();
        } else {
            $row = $DB->query("select * from pay_regcode where type=2 and code='$code' and email='$email' order by id desc limit 1")->fetch();
        }
        if (!$row) {
            exit('{"code":-1,"msg":"验证码不正确！"}');
        }
        if ($row['time'] < time() - 3600 || $row['status'] > 0) {
            exit('{"code":-1,"msg":"验证码已失效，请重新获取"}');
        }
        if ($conf['verifytype'] == 1) {
            $sqs = $DB->exec("update `pay_user` set `phone` ='{$phone}' where `id`='$pid'");
        } else {
            $sqs = $DB->exec("update `pay_user` set `email` ='{$email}' where `id`='$pid'");
        }
        if ($sqs || $DB->errorCode() == '0000') {
            exit('{"code":1,"msg":"succ"}');
        } else {
            exit('{"code":-1,"msg":"保存失败！' . $DB->errorCode() . '"}');
        }
        break;
    case 'checkbind':
        if ($conf['verifytype'] == 1 && (empty($userrow['phone']) || strlen($userrow['phone']) != 11)) {
            exit('{"code":1,"msg":"bind"}');
        } elseif ($conf['verifytype'] == 0 && (empty($userrow['email']) || strpos($userrow['email'], '@') === false)) {
            exit('{"code":1,"msg":"bind"}');
        } elseif (isset($_SESSION['verify_ok']) && $_SESSION['verify_ok'] === $pid) {
            exit('{"code":1,"msg":"bind"}');
        } else {
            exit('{"code":2,"msg":"need verify"}');
        }
        break;
    case 'newOrder':
        session_write_close();
        $pid = $userrow['id'];
        $sid = md5('order_' . $pid . '_time');
        session_start();
        $time = isset($_SESSION[$sid]) && $_SESSION[$sid] > date('Y-m-d H:i:s', time() - 60) ? $_SESSION[$sid] : date('Y-m-d H:i:s', time() - 60);
        session_write_close();
        $data = $DB->query("select trade_no,out_trade_no,type,money,endtime from `pay_order` where `endtime` > '{$time}' and `pid` = {$pid} and status = 1 ORDER BY `endtime` DESC LIMIT 10")->fetchAll(\PDO::FETCH_ASSOC);
        session_start();
        if (!empty($data)) {
            $_SESSION[$sid] = isset($data[0]['endtime']) ? $data[0]['endtime'] : $time;
        } else {
            $_SESSION[$sid] = $time;
        }
        session_write_close();
        die('{"code": 1, "number": ' . count($data) . ', "msg": "success", "data": ' . json_encode($data) . '}');

        break;
    default:
        exit('{"code":-4,"msg":"No Act"}');
        break;
}
